接著建立登入功能
在流程控制這邊追加 login 功能
controller\flowController.js
const viewPrinter = require("../view/viewPrinter");
const telegramItem = require("../interface/telegramItem");
const GetInstanceClass = require("../component/GetInstanceClass");
class FlowController extends GetInstanceClass {
constructor() {
super();
}
/**
* @description 起始畫面
*
* @memberof FlowController
*/
async start() {
await viewPrinter.welcome();
this.mainMenu();
}
/**
* @description 主要選單
*
* @memberof FlowController
*/
async mainMenu() {
let selectOption = await viewPrinter.mainMenu();
switch (selectOption) {
case "登入":
this.loginTelegram();
break;
case "離開":
this.leaveApp();
break;
default:
break;
}
}
/**
* @description 登入 telegram
*
* @memberof FlowController
*/
async loginTelegram() {
await telegramItem.login();
this.mainMenu();
}
/**
* @description 離開應用程式
*
* @memberof FlowController
*/
async leaveApp() {
viewPrinter.clearView();
console.log("按 任意鍵 離開程式");
await viewPrinter.pressToContinue();
process.exit();
}
}
let flowController = FlowController.getInstance();
module.exports = flowController;
然後telegram建立登入功能
interface\telegramItem.js
const { TelegramClient } = require("telegram");
const { StringSession } = require("telegram/sessions");
const { Logger } = require("telegram/extensions");
const input = require("input");
const GetInstanceClass = require("../component/GetInstanceClass");
Logger.setLevel("none"); // 這邊可以隱藏很多關於 telegram 的運作細節
class TelegramItem extends GetInstanceClass {
constructor() {
super();
this.client = null;
}
/**
* @description 初始化 telegram 實體
*
* @memberof TelegramItem
*/
init() {
this.client = new TelegramClient(
new StringSession(""),
Number(process.env.telegramId), // 這邊輸入你的 id
process.env.telegramHash, // 輸入你的 hash
{ connectionRetries: 5 }
);
}
/**
* @description 登入 telegram
*
* @return {*}
* @memberof TelegramClass
*/
async login() {
await this.client.start({
phoneNumber: async () => await input.text("請輸入電話?"),
password: async () => await input.text("請輸入密碼?"),
phoneCode: async () => await input.text("請輸入驗證碼?"),
onError: (err) => console.log("錯誤訊息 : " + err.errorMessage),
});
// console.log(); // Save this string to avoid logging in again
console.log("");
console.log("\x1b[36m", "成功登入");
console.log("");
this.client.session.save();
await this.client.sendMessage("me", {
message: "node sevret is online! " + new Date().toLocaleString(),
});
return true;
}
}
const telegramItem = TelegramItem.getInstance();
telegramItem.init();
module.exports = telegramItem;